require 'base/extender.rb'

# ディレクトリ内のファイルからクラスをロードする．
# [_a-z0-9]+\.rb にマッチしないと，ロードしないよ．
#
# Author:: krdlab
#
class ClassLoader

  # Array includes:
  #     ロード対象を明示する場合に正規表現を指定
  # Array excludes:
  #     ロード除外対象を明示する場合に正規表現を指定
  def initialize(directory, includes=[], excludes=[])
    @directory, @includes, @excludes = directory, includes, excludes
  end

  # return:
  #     クラスの配列
  def collect
    collect_classes(@directory, @includes, @excludes)
  end

private
  def collect_classes(directory, includes, excludes)
    klasses = collect_files(directory, includes, excludes).inject([]) {|ks, f|
      load(f)
      name = get_classname(File.basename(f))
      ks << name.camelize.constantize
    }
    return klasses
  end

  def collect_files(directory, includes, excludes)
    files = []
    Dir.glob(directory + '/*.rb').each {|f|
      files << f if match_file?(f, includes, excludes)
    }
    return files
  end

  def match_file?(f, includes, excludes)
    hit = false
    includes.each {|reg|
      hit = true; break if reg =~ f
    }
    return true if hit
    excludes.each {|reg|
      hit = true; break if reg =~ f
    }
    return false if hit
    return true
  end

  def get_classname(filename)
    return *filename.scan(/([_a-z0-9]+)\.rb/).first
  end
end

